package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import com.itheima.health.service.RoleService;
import com.itheima.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author zhangmeng
 * @description
 * @date 2019/9/6
 **/
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @DubboReference
    private UserService userService;
    @DubboReference
    private RoleService roleService;
    /**
     * 获取当前登录用户名
     *
     * @return
     */
    @GetMapping("/getUsername")
    public Result getUsername() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (null != principal && principal instanceof org.springframework.security.core.userdetails.User) {
            org.springframework.security.core.userdetails.User user = (org.springframework.security.core.userdetails.User) principal;
            return new Result(true, MessageConst.GET_USERNAME_SUCCESS, user.getUsername());
        }
        return new Result(false, MessageConst.GET_USERNAME_FAIL);
    }
    @RequestMapping("/loginSuccess")
    public  Result loginSuccess(){
        return new Result(true, MessageConst.LOGIN_SUCCESS);
    }
    @RequestMapping("/loginFail")
    public Result loginFail(){
        return new Result(false,"登录失败");
    }
    /**
     * @Author: Administrator
     * @Date: 9:48 2021/1/19
     * @Parms [queryPageBean]
     * @ReturnType: com.itheima.health.entity.Result
     * @Description: 分页查询用户信息
    */
    @PreAuthorize("hasAnyAuthority('USER_QUERY','ROLE_ADMIN')")
    @GetMapping("findPage")
    public Result findPage(QueryPageBean queryPageBean) {
        PageResult pageResult=userService.findPage(queryPageBean);
        return new Result(true,MessageConst.ACTION_SUCCESS,pageResult);
    }
    /**
     * @Author: Administrator
     * @Date: 10:58 2021/1/19
     * @Parms [user, roleIds]
     * @ReturnType: com.itheima.health.entity.Result
     * @Description: 新增用户
    */
    @PreAuthorize("hasAnyAuthority('USER_ADD','ROLE_ADMIN')")
    @PostMapping("add")
    public Result add(@RequestBody User user,Integer[] roleIds){
        if (null==user.getUsername()){
            return new Result(false,"用户名不能为空");
        }
        //对密码进行加密
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
        user.setPassword("{bcrypt}"+bCryptPasswordEncoder.encode(user.getPassword()));
        //调用service层添加用户
        boolean flag=userService.add(user,roleIds);
        if (flag){
            //用户添加成功
            return new Result(true,MessageConst.ACTION_SUCCESS);
        }
        //用户已存在,添加失败
        return new Result(false,"该用户已存在,不能添加");
    }
    /**
     * @Author: Administrator
     * @Date: 11:57 2021/1/19
     * @Parms [id]
     * @ReturnType: com.itheima.health.entity.Result
     * @Description: 根据用户id查询用户
    */
    @GetMapping("findById")
    public Result findById(Integer id){
        User user =userService.findById(id);
        return new Result(true,MessageConst.ACTION_SUCCESS,user);
    }
    /**
     * @Author: Administrator
     * @Date: 12:27 2021/1/19
     * @Parms []
     * @ReturnType: com.itheima.health.entity.Result
     * @Description: 查询所有角色信息
    */
    @GetMapping("findAllRole")
    public Result findAllRole(){
        log.info("[查询所有角色信息]");
        List<Role> list=roleService.findAll();
        return new Result(true, MessageConst.ACTION_SUCCESS,list);
    }
    /**
     * @Author: Administrator
     * @Date: 14:27 2021/1/19
     * @Parms [userId]
     * @ReturnType: com.itheima.health.entity.Result
     * @Description: 根据用户id查询角色id
    */
    @GetMapping("findRoleIdsByUserId")
    public Result findRoleIdsByUserId(String userId){
        log.info("[根据用户id查询角色id]:{}",userId);
        List<Integer> list=userService.findRoleIdsByUserId(userId);
        return new Result(true,MessageConst.ACTION_SUCCESS,list);
    }
    /**
     * @Author: Administrator
     * @Date: 14:44 2021/1/19
     * @Parms [user, roleIds]
     * @ReturnType: com.itheima.health.entity.Result
     * @Description: 编辑用户信息
    */
    @PreAuthorize("hasAnyAuthority('USER_EDIT','ROLE_ADMIN')")
    @PostMapping("edit")
    public Result edit(@RequestBody User user, Integer[] roleIds){
        log.info("[编辑用户信息]用户:{},roleIds:{}",user,roleIds);
        //通过id查询用户原始数据
        User userbyId = userService.findById(user.getId());
        log.info("[==========原始密码:]:{}",userbyId.getPassword());
        log.info("[=====页面传递的密码]:{}",user.getPassword());
        //判断编辑后的密码与原密码是否一致 如果不一致 就对新密码加密
        if (!user.getPassword().equals(userbyId.getPassword())){
            log.info("[===========对新密码进行加密]");
            BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
            user.setPassword("{bcrypt}"+bCryptPasswordEncoder.encode(user.getPassword()));
        }
        userService.edit(user,roleIds);
        return new Result(true,MessageConst.ACTION_SUCCESS);
    }
    /**
     * @Author: Administrator
     * @Date: 15:10 2021/1/19
     * @Parms [userId]
     * @ReturnType: com.itheima.health.entity.Result
     * @Description: 删除用户信息
    */
    @PreAuthorize("hasAnyAuthority('USER_DELETE','ROLE_ADMIN')")
    @RequestMapping("delete")
    public Result delete(Integer userId){
        log.info("======================================================================");
        log.info("[删除用户信息]userId:{}",userId);
        userService.deleteByUserId(userId);
        return new Result(true,MessageConst.ACTION_SUCCESS);
    }


    public static void main(String[] args) {
        System.out.println("====");
    }
}
